package sy1and2;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

public class ArithmeticQuestionGenerator {
    private static final Random random = new Random(); // 全局随机数生成器

    // 生成算术题的方法
    public static List<String> generateQuestions(String operatorType, boolean isThreeNumbers, int numQuestions) {
        List<String> questions = new ArrayList<>();
        for (int i = 0; i < numQuestions; i++) {
            String question;
            do {
                // 根据运算类型生成符合条件的题目
                if ("加法".equals(operatorType)) {
                    question = generateAdditionQuestion(isThreeNumbers);
                } else if ("减法".equals(operatorType)) {
                    question = generateSubtractionQuestion(isThreeNumbers);
                } else if ("乘法".equals(operatorType)) {
                    question = generateMultiplicationQuestion(isThreeNumbers);
                } else if ("除法".equals(operatorType)) {
                    question = generateDivisionQuestion(isThreeNumbers);
                } else if ("加减混合".equals(operatorType)) {
                    question = generateAddSubMixedQuestion(isThreeNumbers);
                } else if ("乘除混合".equals(operatorType)) {
                    question = generateMulDivMixedQuestion(isThreeNumbers);
                } else if ("四则运算".equals(operatorType)) {
                    question = generateFourMixedQuestion(isThreeNumbers);
                } else {
                    question = "无效的运算类型";
                    break; // 无效类型直接退出循环
                }
            } while (!isResultValid(question)); // 验证结果是否在(0,100)范围

            questions.add(question);
        }
        return questions;
    }

    // 生成加法题目
    private static String generateAdditionQuestion(boolean isThreeNumbers) {
        int numCount = isThreeNumbers ? 3 : 2;
        int[] nums = new int[numCount];
        int sum;
        do {
            sum = 0;
            for (int i = 0; i < numCount; i++) {
                nums[i] = random.nextInt(98) + 1; // 1-98之间，避免单个数字过大
                sum += nums[i];
            }
        } while (sum <= 0 || sum >= 100); // 确保和在(0,100)

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < numCount; i++) {
            if (i > 0) sb.append(" + ");
            sb.append(nums[i]);
        }
        sb.append(" = ");
        return sb.toString();
    }

    // 生成减法题目
    private static String generateSubtractionQuestion(boolean isThreeNumbers) {
        if (isThreeNumbers) {
            int a, b, c, result;
            do {
                a = random.nextInt(98) + 2; // 确保至少能减两次
                b = random.nextInt(a - 1) + 1; // b < a
                while (a - b - 1 <= 0) {
                    a = random.nextInt(98) + 2;
                    b = random.nextInt(a - 1) + 1;
                }
                c = random.nextInt(a - b - 1) + 1; // c < a-b
                result = a - b - c;
            } while (result <= 0 || result >= 100); // 确保结果在(0,100)

            return a + " - " + b + " - " + c + " = ";
        } else {
            int a, b, result;
            do {
                a = random.nextInt(98) + 2; // 至少比1大
                b = random.nextInt(a - 1) + 1; // b < a
                result = a - b;
            } while (result <= 0 || result >= 100);

            return a + " - " + b + " = ";
        }
    }

    // 生成乘法题目
    private static String generateMultiplicationQuestion(boolean isThreeNumbers) {
        int numCount = isThreeNumbers ? 3 : 2;
        int[] nums = new int[numCount];
        int product;
        do {
            product = 1;
            for (int i = 0; i < numCount; i++) {
                nums[i] = random.nextInt(9) + 1; // 乘法数字控制在1-9，避免结果过大
                product *= nums[i];
            }
        } while (product <= 0 || product >= 100);

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < numCount; i++) {
            if (i > 0) sb.append(" × ");
            sb.append(nums[i]);
        }
        sb.append(" = ");
        return sb.toString();
    }

    // 生成除法题目（确保整除，结果为正整数）
    private static String generateDivisionQuestion(boolean isThreeNumbers) {
        if (isThreeNumbers) {
            int a, b, c, result;
            do {
                b = random.nextInt(9) + 1;
                c = random.nextInt(9) + 1;
                int bc = b * c;
                a = bc * (random.nextInt(9) + 1); // 确保a是bc的倍数，且结果<100
                result = a / b / c;
            } while (result <= 0 || result >= 100 || a >= 100);

            return a + " ÷ " + b + " ÷ " + c + " = ";
        } else {
            int a, b, result;
            do {
                b = random.nextInt(9) + 1;
                a = b * (random.nextInt(9) + 1); // 确保a是b的倍数
                result = a / b;
            } while (result <= 0 || result >= 100 || a >= 100);

            return a + " ÷ " + b + " = ";
        }
    }

    // 生成加减混合运算题目（原混合运算）
    private static String generateAddSubMixedQuestion(boolean isThreeNumbers) {
        int numCount = isThreeNumbers ? 3 : 2;
        int[] nums = new int[numCount];
        String[] ops = new String[numCount - 1];
        int result;

        do {
            // 生成数字
            for (int i = 0; i < numCount; i++) {
                nums[i] = random.nextInt(98) + 1;
            }
            // 生成运算符
            for (int i = 0; i < ops.length; i++) {
                ops[i] = random.nextBoolean() ? "+" : "-";
            }
            // 计算结果
            result = nums[0];
            for (int i = 0; i < ops.length; i++) {
                if ("+".equals(ops[i])) {
                    result += nums[i + 1];
                } else {
                    result -= nums[i + 1];
                }
            }
        } while (result <= 0 || result >= 100); // 确保结果有效

        // 构建题目字符串
        StringBuilder sb = new StringBuilder().append(nums[0]);
        for (int i = 0; i < ops.length; i++) {
            sb.append(" ").append(ops[i]).append(" ").append(nums[i + 1]);
        }
        sb.append(" = ");
        return sb.toString();
    }

    // 乘除混合
    private static String generateMulDivMixedQuestion(boolean isThreeNumbers) {
        int numCount = isThreeNumbers ? 3 : 2;
        int[] nums = new int[numCount];
        String[] ops = new String[numCount - 1];
        int result;

        do {
            for (int i = 0; i < numCount; i++) {
                nums[i] = random.nextInt(9) + 1; // 乘除数字控制在1-9
            }
            for (int i = 0; i < ops.length; i++) {
                ops[i] = random.nextBoolean() ? "×" : "÷";
            }
            result = nums[0];
            for (int i = 0; i < ops.length; i++) {
                if ("×".equals(ops[i])) {
                    result *= nums[i + 1];
                } else {
                    result /= nums[i + 1];
                }
            }
        } while (result <= 0 || result >= 100);

        StringBuilder sb = new StringBuilder().append(nums[0]);
        for (int i = 0; i < ops.length; i++) {
            sb.append(" ").append(ops[i]).append(" ").append(nums[i + 1]);
        }
        sb.append(" = ");
        return sb.toString();
    }

    // 四则混合（三个数加减乘除混合，必须包含至少一个加减和一个乘除）
    private static String generateFourMixedQuestion(boolean isThreeNumbers) {
        if (!isThreeNumbers) {
            return "四则混合仅支持三个数运算";
        }
        int[] nums = new int[3];
        String[] ops = new String[2];
        int result;

        do {
            result = -1; // 初始化无效值，确保循环能正常判断
            nums[0] = random.nextInt(98) + 1; // 1-98
            nums[1] = random.nextInt(9) + 1;  // 1-9（避免乘除结果过大）
            nums[2] = random.nextInt(9) + 1;  // 1-9

            // 确保运算符同时包含：至少1个加减（+/-）和至少1个乘除（×/÷）
            boolean hasMulDiv = false; // 是否包含乘除
            boolean hasAddSub = false; // 是否包含加减
            while (!hasMulDiv || !hasAddSub) { // 循环直到两个条件都满足
                hasMulDiv = false;
                hasAddSub = false;
                for (int i = 0; i < 2; i++) {
                    int opIdx = random.nextInt(4); // 0:+ 1:- 2:× 3:÷
                    ops[i] = opIdx == 0 ? "+" : opIdx == 1 ? "-" : opIdx == 2 ? "×" : "÷";
                    // 更新标记
                    if ("×".equals(ops[i]) || "÷".equals(ops[i])) {
                        hasMulDiv = true;
                    } else {
                        hasAddSub = true;
                    }
                }
            }

            // 先处理乘除运算（遵循优先级）
            List<Integer> numsList = new ArrayList<>();
            List<String> opsList = new ArrayList<>();
            numsList.add(nums[0]); // 初始数字

            for (int i = 0; i < 2; i++) {
                String op = ops[i];
                int nextNum = nums[i + 1];
                if ("×".equals(op) || "÷".equals(op)) {
                    // 立即计算乘除
                    int lastNum = numsList.remove(numsList.size() - 1);
                    if ("×".equals(op)) {
                        numsList.add(lastNum * nextNum);
                    } else { // 除法确保整除
                        if (lastNum % nextNum != 0) {
                            numsList.clear(); // 标记为无效
                            break;
                        }
                        numsList.add(lastNum / nextNum);
                    }
                } else {
                    // 加减暂存，后续处理
                    opsList.add(op);
                    numsList.add(nextNum);
                }
            }

            // 若乘除处理中出现无效情况（如非整除），跳过当前循环
            if (numsList.isEmpty()) {
                continue;
            }

            // 再处理加减运算
            result = numsList.get(0);
            for (int i = 0; i < opsList.size(); i++) {
                String op = opsList.get(i);
                int num = numsList.get(i + 1);
                if ("+".equals(op)) {
                    result += num;
                } else {
                    result -= num;
                }
            }

        } while (result <= 0 || result >= 100); // 确保结果在(0,100)之间

        // 拼接题目字符串
        StringBuilder sb = new StringBuilder().append(nums[0]);
        for (int i = 0; i < 2; i++) {
            sb.append(" ").append(ops[i]).append(" ").append(nums[i + 1]);
        }
        sb.append(" = ");
        return sb.toString();
    }


    // 验证题目结果是否在(0,100)范围
 static boolean isResultValid(String question) {
        if (question.contains("无效的运算类型")) {
            return true;
        }
        try {
            String expr = question.replace(" = ", "");
            String[] parts = expr.split(" ");
            List<Integer> nums = new ArrayList<>();
            List<String> ops = new ArrayList<>();
            nums.add(Integer.parseInt(parts[0]));
            for (int i = 1; i < parts.length; i += 2) {
                String op = parts[i];
                int num = Integer.parseInt(parts[i + 1]);
                if ("×".equals(op) || "÷".equals(op)) {
                    int last = nums.remove(nums.size() - 1);
                    if ("×".equals(op)) {
                        nums.add(last * num);
                    } else {
                        if (last % num != 0) {
                            return false;
                        }
                        nums.add(last / num);
                    }
                } else {
                    ops.add(op);
                    nums.add(num);
                }
            }
            int result = nums.get(0);
            for (int i = 0; i < ops.size(); i++) {
                String op = ops.get(i);
                int num = nums.get(i + 1);
                if ("+".equals(op)) {
                    result += num;
                } else {
                    result -= num;
                }
            }
            return result > 0 && result < 100;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    // 输出到CSV并格式化展示
    public static void exportToCSV(List<String> questions, int colsPerRow, String filePath) {
        try {
            List<String> rows = new ArrayList<>();
            StringBuilder row = new StringBuilder();
            for (int i = 0; i < questions.size(); i++) {
                row.append(questions.get(i)).append(",");
                if ((i + 1) % colsPerRow == 0 || i == questions.size() - 1) {
                    rows.add(row.toString().trim().replaceAll(",$", ""));
                    row.setLength(0);
                }
            }

            // 写入带UTF-8 BOM的文件
            byte[] bom = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
            Files.write(Paths.get(filePath), bom); // 先写BOM头
            Files.write(Paths.get(filePath), rows, StandardCharsets.UTF_8, java.nio.file.StandardOpenOption.APPEND);

            System.out.println("已保存到 " + filePath + "（UTF-8带BOM）");
        } catch (Exception e) {
            System.out.println("保存失败：" + e.getMessage());
        }
    }


    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择运算类型（加法/减法/乘法/除法/加减混合/乘除混合/四则运算）：");
        String operatorType = scanner.nextLine();
        System.out.println("是否生成三个数的题目（true/false）：");
        boolean isThreeNumbers = Boolean.parseBoolean(scanner.nextLine());
        System.out.println("请输入题目数量：");
        int numQuestions = scanner.nextInt();
        System.out.println("请输入每行列数：");
        int colsPerRow = scanner.nextInt();
        System.out.println("请输入CSV文件路径（如 questions.csv）：");
        String filePath = scanner.next();

        List<String> questions = generateQuestions(operatorType, isThreeNumbers, numQuestions);
        for (int i = 0; i < questions.size(); i++) {
            System.out.println((i + 1) + ". " + questions.get(i));
        }
        exportToCSV(questions, colsPerRow, filePath);
        scanner.close();
    }
}